import random
from sys import maxint
import datetime
import os
from tempfile import TemporaryFile
import cStringIO


# It was important to put this 'Agg' line before the pylab import
# to avoid a memory leak when plotting over and over
# See http://mail.python.org/pipermail/python-list/2006-December/417208.html
# NOTE: If want to display, put the 'from' line before the 'Agg' line.
import matplotlib
matplotlib.use('Cairo')
from pylab import *
from dbquery import executeQuery
import random

largePlotSize = (4, 3)
color = 'b'

def plotSolarDay(times, totals, minTime, maxTime, graphTitle, filename, closeFig):

  fig = figure(None, largePlotSize, 300, None, None)
  ax=fig.add_subplot(111)
  ax.plot(times, totals, color)
  ax.set_ylim([0,3000])
  ax.set_xlim([minTime, maxTime])
  #ax.legend(('Total Power',)  )
  # xlabel('Hour')
  #ylabel('Watts')
  ax.grid(False)
  title('Watts')


  interval = ((len(times)/4)/2)
  # set the x-axis to display hours
  ax.xaxis.set_major_locator(HourLocator(interval= interval))
  # could use %p to get am/pm below, but too cluttered
  hourFmt = DateFormatter( interval > 10 and "%m-%d" or "%H:%M" )
  ax.xaxis.set_major_formatter(hourFmt)

  # save to a file
  if (filename != ""):
    fig.savefig(filename, format='png')

  if (closeFig):
    close(fig)
    
def barChart(labels, label, points, filename):
  fig = figure(None, largePlotSize, 300, None, None)
  bar1 = bar(arange(len(labels)), points, .75, color = color)
  xticks(arange(len(labels)) + .375, labels )
  title(label)
  ylabel("kWh")
  if (filename != ""):
    fig.savefig(filename, format='png')
  close(fig)
    
def drawChart(hours):
  rows = executeQuery("select time, watts from solar_data where time" + 
  "> TIMESTAMPADD(HOUR,-%s,NOW()) and watts IS NOT NULL order by time desc" % hours)
  times = map(lambda x: date2num(x[0]), rows)
  totals = map(lambda x: x[1], rows)
  file = cStringIO.StringIO() #TemporaryFile() 
  plotSolarDay(times, totals, times[-1], times[0], "Output", file, True)
  return file
  
  
def drawBarChart(type):
  if type == 'total':
    query = "select date(time), max(kwh_today) from solar_data where  time(time) > maketime(7,00,0) group by date(time) order by date(time) desc"
    label = "kWh Total"
  else:
    query = "select date(time), max(kwh_today) from solar_data where time(time) > maketime(7,00,0) and  time(time) < time(now()) group by date(time) order by date(time) desc"  
    label = "kWh at " + datetime.datetime.now().strftime("%I:%M%p")
  rows = [ x for x in reversed(executeQuery(query)[:7])]
  labels = map(lambda x: x[0].strftime("%m-%d"), rows)
  points = map(lambda x: x[1], rows)
  file = cStringIO.StringIO()
  barChart(labels, label, points, file)
  return file
  
  
if __name__ == "__main__":
  file = drawChart(1)
  file.seek(0)
  out = open('chart.png', 'wb')
  out.write(file.read())
  out.close()

  
